let util = require('../../utils/util');

let requestDomain = util.config('requestDomain');

let that;

Page({
    data: {
        myRoleInfoList: [],
        serviceList: [],
        addService: false,
        serviceAuthType: {
            admin: '管理员',
            service: '服务员'
        },
        serviceName: null,
        serviceAuth: null,
        serviceAuthInput: '',
        registerCode: '',
        showRegisterCodeGroup: false,
        admin: false
    },
    onLoad: function() {
        that = this;
        if(util.globalData('serviceAuth') == 'admin') {
            that.setData({admin: true});
        }
        let serviceTableNums = '';
        if (util.globalData('serviceTableNums') == '*') {
            serviceTableNums = '*';
        }
        else {
            let serviceTableNumList = util.globalData('serviceTableNums');
            let nowNum = '';
            let nowPrefix = '';
            let num = '';
            let prefix = '';
            let toLastNum,lastNum, nextNum, nextPrefix;
            for (let tableIndex in serviceTableNumList) {
                if (serviceTableNumList.length == 1) {
                    serviceTableNums = serviceTableNumList[0];
                    break;
                }
                nowNum = serviceTableNumList[tableIndex].replace(/[^0-9]/ig, '');
                nowPrefix = serviceTableNumList[tableIndex].substr(0, serviceTableNumList[tableIndex].indexOf(nowNum));
                if (nowNum == '') {
                    serviceTableNums += serviceTableNums == '' ? serviceTableNumList[tableIndex] : (',' + serviceTableNumList[tableIndex]);
                }
                else if (prefix != nowPrefix) {
                    if (serviceTableNums == '') {
                        serviceTableNums += serviceTableNumList[tableIndex];
                    }
                    else {
                        toLastNum = serviceTableNumList[tableIndex - 2].replace(/[^0-9]/ig, '');
                        lastNum = serviceTableNumList[tableIndex - 1].replace(/[^0-9]/ig, '');
                        if (lastNum - toLastNum != 1) {
                            serviceTableNums += ',' + serviceTableNumList[tableIndex - 1] + ',' + serviceTableNumList[tableIndex];
                        }
                        else {
                            serviceTableNums += '-' + lastNum + ',' + serviceTableNumList[tableIndex];
                        } 
                    }
                    prefix = nowPrefix;
                }
                else if (tableIndex == serviceTableNumList.length - 1) {
                    serviceTableNums += '-' + nowNum;
                }
                else {
                    lastNum = serviceTableNumList[tableIndex - 1].replace(/[^0-9]/ig, '');
                    nextNum = serviceTableNumList[parseInt(tableIndex) + 1].replace(/[^0-9]/ig, '');
                    nextPrefix = serviceTableNumList[parseInt(tableIndex) + 1].substr(0, serviceTableNumList[parseInt(tableIndex) + 1].indexOf(nextNum));
                    if (nextPrefix != nowPrefix) {
                        
                    }
                    else if (nowNum - lastNum != 1) {
                        serviceTableNums += ',' + serviceTableNumList[tableIndex];
                    }
                    else if(nextNum - nowNum != 1) {
                        serviceTableNums += '-' + serviceTableNumList[tableIndex];
                    }
                }
            }
        }
        //存放个人信息列表
        let myRoleInfoList = [
            { infoId: 'auth', infoName: '我的权限', infoVal: that.getAuthName(util.globalData('serviceAuth')), tip: '*号代表您负责所有顾客，添加桌号请使用逗号分隔不同桌号，如A1,A2,A3,A4，也可以使用如A1-4来代替前者，多个类型的桌号前缀可用A1-10,B1-10来完成桌号添加', maxLength: 800 },
            {infoId: 'name', infoName: '我的昵称', infoVal: util.globalData('serviceName'), maxLength: 8},
            { infoId: 'tableNums', infoName: '负责范围', infoVal: serviceTableNums, tip: '*号代表您负责所有顾客，添加桌号请使用逗号分隔不同桌号，如A1,A2,A3,A4，也可以使用如A1-4来代替前者，多个类型的桌号前缀可用A1-10,B1-10来完成桌号添加', maxLength: 800}
        ];
        that.getAllowServices();
        //更新数据到页面
        that.setData({myRoleInfoList: myRoleInfoList});
    },
    onShow: function () {
        if (util.globalData('lastEditInfo')) {
            let {infoId, infoVal} = util.globalData('lastEditInfo');
            let {myRoleInfoList} = that.data;
            for (let infoIndex in myRoleInfoList) {
                if (myRoleInfoList[infoIndex].infoId == infoId) {
                    myRoleInfoList[infoIndex].infoVal = infoVal;
                    break;
                }
            }
            that.setData({ myRoleInfoList: myRoleInfoList });
            util.globalData('lastEditInfo', null);
        }
    },
    getAllowServices: function() {
        wx.showNavigationBarLoading();
        wx.request({
            url: requestDomain + 'store/getAllowServices',
            method: 'POST',
            data: {
                storeId: util.globalData('storeId'),
                _3rdSession: util.globalData('_3rdSession')
            },
            success: function(result) {
                wx.hideNavigationBarLoading();
                if(util.checkSuccess(result) && result.data && result.data.data) {
                    let serviceList = [];
                    let allowServices = result.data.data;
                    for (let serviceIndex in allowServices) {
                        serviceList.push({
                            serviceId: allowServices[serviceIndex].id,
                            serviceName: allowServices[serviceIndex].name,
                            serviceAuth: that.getAuthName(allowServices[serviceIndex].auth),
                            serviceTableNums: allowServices[serviceIndex].tableNums
                        });
                    }
                    that.setData({ serviceList: serviceList });
                }
                else {
                    util.showError('获取失败', '获取角色列表失败' + result.data.errMsg, result.data.errCode);
                }
                wx.stopPullDownRefresh();
            },
            fail: function() {
                wx.hideNavigationBarLoading();
                wx.stopPullDownRefresh();
                util.showError('获取失败', '获取角色列表失败');
            }
        });
    },
    editRoleInfo: function(e) {
        let infoId = e.currentTarget.dataset.infoid;
        let myRoleInfoList = that.data.myRoleInfoList;
        if(infoId == 'auth') {
            return;
        }
        for(let infoIndex in myRoleInfoList) {
            if(myRoleInfoList[infoIndex].infoId == infoId) {
                let {infoName, infoVal, tip, maxLength} = myRoleInfoList[infoIndex];
                wx.navigateTo({
                    url: '/pages/editStoreInfo/editStoreInfo?dataType=roleInfo&infoId=' + infoId + '&infoName=' + infoName + '&infoVal=' + infoVal + '&tip=' + tip + '&maxLength=' + maxLength,
                    fail: function () {
                        wx.showModal({
                            title: '跳转失败',
                            content: '跳转到修改信息页面失败'
                        });
                    }
                });
            }
        }
    },
    serviceNameInput: function(e) {
        let serviceName = e.detail.value;
        that.setData({
            serviceName: serviceName
        });
    },
    chooseServiceAuth: function() {
        let {serviceAuthType} = that.data;
        let itemList = [];
        let authIdList = [];
        for (let authIndex in serviceAuthType) {
            itemList.push(serviceAuthType[authIndex]);
            authIdList.push(authIndex);
        }
        wx.showActionSheet({
            itemList: itemList,
            success: function(result) {
                console.log(authIdList[result.tapIndex]);
                that.setData({
                    serviceAuth: itemList[result.tapIndex],
                    serviceAuthInput: authIdList[result.tapIndex]
                });
            }
        });
    },
    addService: function() {
        let {addService, serviceName, serviceAuthInput} = that.data;
        //判断是否处于添加角色状态
        if(addService) {
            wx.showNavigationBarLoading();
            wx.request({
                url: requestDomain + 'register/getAddServiceCode',
                method: 'POST',
                data: {
                    storeId: util.globalData('storeId'),
                    _3rdSession: util.globalData('_3rdSession'),
                    serviceName: serviceName,
                    serviceAuth: serviceAuthInput
                },
                success: function(result) {
                    wx.hideNavigationBarLoading();  
                    if(util.checkSuccess(result) && result.data && result.data.data) {
                        let {registerCode} = result.data.data;
                        that.setData({ addService: false });
                        that.setData({
                            registerCode: registerCode,
                            showRegisterCodeGroup: true
                        });
                    }
                    else {
                        util.showError('添加失败', '系统在处理添加角色请求时出现错误' + result.data.errMsg, result.data.errCode);
                    }
                },
                fail: function() {
                    wx.hideNavigationBarLoading();
                    util.showError('添加失败', '发起添加角色请求失败');
                }
            });
        }
        else {
            that.setData({ addService: true });
        }
    },
    getAuthName: function(authId) {
        let {serviceAuthType} = that.data;
        for(let authIndex in serviceAuthType) {
            if (authIndex == authId) {
                return serviceAuthType[authIndex];
            }
        }
        return '未知';
    },
    hideRegisterGroup: function() {
        wx.showModal({
            title: '确认关闭？',
            content: '请记住此激活码，有效期为30分钟，是否关闭此窗口？',
            success: function(modal) {
                if(modal.confirm) {
                    that.setData({ showRegisterCodeGroup: false });
                }
            }
        });
    },
    serviceItemClick: function(e) {
        let serviceId = e.currentTarget.dataset.serviceid;
        let {serviceList} = that.data;
        wx.showActionSheet({
            itemList: ['查看负责范围', '删除此角色'],
            success: function(result) {
                for (let serviceIndex in serviceList) {
                    if (serviceList[serviceIndex].serviceId == serviceId) {
                        if (result.tapIndex == 0) {
                            wx.showModal({
                                title: serviceList[serviceIndex].serviceName,
                                content: '此角色负责的桌号范围为' + (serviceList[serviceIndex].serviceTableNums == '*' ? '所有' : (serviceList[serviceIndex].serviceTableNums.join(',')))
                            });
                        }
                        else if (result.tapIndex == 1) {
                            if (serviceList[serviceIndex].serviceName == util.globalData('serviceName')) {
                                wx.showModal({
                                    title: '错误提示',
                                    content: '不能删除自己'
                                });
                            }
                            else {
                                wx.showNavigationBarLoading();
                                wx.request({
                                    url: requestDomain + 'store/delAllowService',
                                    method: 'POST',
                                    data: {
                                        storeId: util.globalData('storeId'),
                                        _3rdSession: util.globalData('_3rdSession'),
                                        serviceId: serviceId
                                    },
                                    success: function(result) {
                                        wx.hideNavigationBarLoading();
                                        if(util.checkSuccess(result) && result.data && result.data.data) {
                                            wx.showToast({
                                                title: '删除成功',
                                                icon: 'success'
                                            });
                                            let temp = [];
                                            for (let serviceIndex in serviceList) {
                                                if (serviceList[serviceIndex].serviceId != serviceId) {
                                                    temp.push(serviceList[serviceIndex]);
                                                }
                                            }
                                            that.setData({ serviceList: temp });
                                        }
                                        else {
                                            util.showError('删除失败', '删除角色失败' + result.data.errMsg, result.data.errCode);
                                        }
                                    },
                                    fail: function() {
                                        wx.hideNavigationBarLoading();
                                        util.showError('删除失败', '发起删除角色请求失败')
                                    }
                                });
                            }
                        }
                        break;
                    }
                }
            }
        });        
    },

    onPullDownRefresh: function() {
        that.getAllowServices();
    }
});